package com.lnj.community.controller;

import com.lnj.community.config.JwtConfig;
import com.lnj.community.dao.entity.User;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.CommunityConstant;
import com.lnj.community.utiles.HostHolder;
import com.lnj.community.utiles.JwtUtil;
import com.lnj.community.utiles.RedisKeyUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController implements CommunityConstant {
    @Autowired
    private UserService userService;

    @Value("${server.servlet.context-path}")
    String contextPath ; // 注入项目名称
    @Value("${community.path.domain}")
    String domain ; // 注入域名
    @Autowired
    private JwtConfig jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;



    private static final Logger log= LoggerFactory.getLogger(LoginController.class);

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getLoginPage(HttpServletRequest request) {

        return "/site/login";
    }
    /**
     * 跳转到注册页面
     * @return
     */
    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String getRegisterPage() {

        return "/site/register";
    }
    /**
     * 注册用户
     * @param user
     * @return 返回一个map，包含注册结果信息
     *         注册成功：map为空，即注册成功
     *         注册失败：map包含错误信息，即注册失败
     */
    @RequestMapping(path = "register", method = RequestMethod.POST)
    public String register(Model model,User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经向您的邮箱发送了一封激活邮件，请尽快激活！");
            //跳转到首页
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        } else {
            if(map.containsKey("usernameMsg")){
                model.addAttribute("usernameMsg", map.get("usernameMsg"));
            }
            if(map.containsKey("passwordMsg")){
                model.addAttribute("passwordMsg", map.get("passwordMsg"));
            }
            if(map.containsKey("emailMsg")){
                model.addAttribute("emailMsg", map.get("emailMsg"));
            }
            return "/site/register";
        }
    }
    /**
     * 激活用户
     * @param userId
     * @param code
     * @return
     */
    @RequestMapping(path = "activation/{userId}/{code}", method = RequestMethod.GET)
    public String activation(Model model, @PathVariable(name = "userId") int userId,@PathVariable(name = "code") String code) {
        //获取激活结果
        int result = userService.activation(userId, code);
        if (result==ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功，您的账号已经可以正常使用了！");
            model.addAttribute("target","/login");

        }else if (result==ACTIVATION_REPEAT){
            model.addAttribute("msg","无效操作，该账号已经激活过了！");
            model.addAttribute("target","/index");
        }else {
            model.addAttribute("msg","激活失败，您提供的激活码不正确！");
            model.addAttribute("target","/index");
        }
        return "site/operate-result";
    }

    /**
     * 获取验证码
     * @return
     */
    @RequestMapping(path = "/kaptcha", method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response) {
        //获取验证码图片
        BufferedImage image = userService.getKaptcha(response);
        //将验证码图片输出到浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("响应验证码失败：" + e.getMessage());
        }
    }

    /**
     * 登录
     * @param username 用户名或邮箱
     * @param password 密码
     * @param code 验证码
     * @param rememberme 是否记住我
     * @param model 模型
     * @param response 响应 存cookie
     * @return
     */
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(String username, String password, String code, boolean rememberme,
                        Model model,  HttpServletResponse response, @CookieValue("kaptchaOwner") String kaptchaOwner) {
        //1.获取验证码
        //String kaptcha = (String) session.getAttribute("kaptcha");
        String kaptcha = null;
        if (StringUtils.isNotBlank(kaptchaOwner)) {
            //从redis中获取验证码
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }
        //2.检查验证码
        if (StringUtils.isBlank(kaptcha)|| StringUtils.isBlank(code)||!kaptcha.equalsIgnoreCase(code)){
            //把参数添加到模板中
            model.addAttribute("username",username);
            model.addAttribute("password",password);
            model.addAttribute("code",code);
            model.addAttribute("rememberme",rememberme);
            model.addAttribute("codeMsg","验证码不正确！");
            return "/site/login";
        }
        //3.检查账号密码
        int expiredSeconds=rememberme?REMEMBER_EXPIRED_SECONDS:DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map=userService.login(username,password,expiredSeconds);


        //4.判断登录结果
        if (map.containsKey(LNJ_TOKEN)){
            Cookie cookie=new Cookie(jwtProperties.getUserTokenName(),map.get(LNJ_TOKEN).toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            //添加用户到localThread
            HostHolder.setUser((User) map.get("user"));

            //跳转到首页
            return "redirect:/index";
        }else {
            //把参数添加到模板中
            model.addAttribute("username",username);
            model.addAttribute("password",password);
            model.addAttribute("code",code);
            model.addAttribute("rememberme",rememberme);
            if(map.containsKey("usernameMsg")){
                model.addAttribute("usernameMsg", map.get("usernameMsg"));
            }
            if(map.containsKey("passwordMsg")){
                model.addAttribute("passwordMsg", map.get("passwordMsg"));
            }
            return "/site/login";
        }

    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public String logout(@CookieValue(LNJ_TOKEN) String token, HttpServletResponse response) {
        //TODO:用redis数据库来设置黑名单
        //userService.logout(token);

        // 清除客户端的 token Cookie
        Cookie cookie = new Cookie(LNJ_TOKEN, null);
        cookie.setPath(contextPath);
        cookie.setMaxAge(0); // 设置 Cookie 立即过期
        response.addCookie(cookie);

        // 清除服务器端的 token
        if (token != null) {
            redisTemplate.delete(RedisKeyUtil.getTokenKey(token));
        }

        // 清除 HostHolder 中的用户信息
        HostHolder.clear();
        //清除SecurityContextHolder中的用户信息
        SecurityContextHolder.clearContext();

        // 跳转到登录页面
        return "redirect:/login";
    }

    // 拒绝访问时的提示页面
    @RequestMapping(path = "/denied", method = RequestMethod.GET)
    public String getDeniedPage() {
        return "/error/404";
    }

}
